package com.eip.zd.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eip.zd.entity.Price;
import com.eip.zd.entity.Prod;
import com.eip.zd.exception.CustomException;
import com.eip.zd.mapper.ProdMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.RoundingMode;
import java.util.List;

@Service
public class ProdService {
    @Resource
    private ProdMapper prodMapper;
    @Resource
    private PriceService priceService;

    public List<Prod> getProdList(String keyword) {
        QueryWrapper<Prod> wrapper = new QueryWrapper<>();
        wrapper.like(keyword != null, "prod_name", keyword).or().like(keyword != null, "prod_id", keyword);
        return prodMapper.selectList(wrapper);
    }

    public void add(Prod prod) {
        if (StrUtil.hasEmpty(prod.getProdId())) {
            throw new CustomException(500, "产品编号不能为空");
        }
        if (prodMapper.selectById(prod.getProdId()) != null) {
            throw new CustomException(500, "该产品已存在");
        }
        prod.setUnitPrice(prod.getUnitPrice().setScale(2, RoundingMode.HALF_UP));
        prodMapper.insert(prod);
    }

    public void update(Prod prod) {
        if (StrUtil.hasEmpty(prod.getProdId())) {
            throw new CustomException(500, "产品编号不能为空");
        }
        prod.setUnitPrice(prod.getUnitPrice().setScale(2, RoundingMode.HALF_UP));
        prodMapper.updateById(prod);
    }

    public void remove(Long id) {
        Prod prod = prodMapper.selectById(id);
        prod.setIfUse(2);
        prodMapper.updateById(prod);
        prodMapper.deleteById(id);
    }

    public void ifUse(Long id) {
        Prod prod = prodMapper.selectById(id);
        if (prod.getIfUse() == 1) {
            prod.setIfUse(2);
        } else {
            prod.setIfUse(1);
        }
        prodMapper.updateById(prod);
    }

    public List<Prod> getTenProd(String keyword) {
        QueryWrapper<Prod> wrapper = new QueryWrapper<>();
        wrapper.eq("if_use", 1).and(qw -> {
            qw.like("prod_name", keyword).or().eq("prod_id", keyword);
        });
        List<Prod> prodList = prodMapper.selectList(wrapper);
        if (prodList.size() > 10) {
            return prodList.subList(0, 10);
        }
        return prodList;

    }

    public List<Prod> getCustProdList(String custId, String keyword) {
        List<Prod> prodList = getProdList(keyword);
        List<Price> priceList = priceService.getPriceList(custId);
        prodList.stream().forEach(prod -> {
            priceList.stream().forEach(price -> {
                if (price.getProdId().equals(prod.getProdId())) {
                    prod.setUnitPrice(price.getPrice());
                }
            });
        });
        return prodList;
    }
}
